<script setup lang="ts">
import InputBar from './InputBar.vue';
import FileTable from './FileTable.vue';
import Loading from './Loading.vue';

import { message } from 'ant-design-vue';
import { onMounted, onUnmounted, ref } from 'vue';
import { FileModel, ScanDir, ScanFileResult } from '../model/model';
import { sendCommand } from '../utils/TauriUtils';
import Result from './Result.vue';
import { listen, UnlistenFn } from '@tauri-apps/api/event';
import { formatFileSize, formatSeconds, sortByFileSize } from '../utils/utils';

// 本次扫描是否完成
const scanFileComplete = ref(false);

const loading = ref(false);
const startTime = ref(new Date());
//当前扫描的文件
const currentScanFilePath = ref("获取信息中...");
// 本次共扫描多少文件
const scanFileNum = ref(0);
const resultTitle = ref("");
const resultSubTitle = ref("");
const fileItemListen = ref<UnlistenFn>();
const fileListResultListen = ref<UnlistenFn>();
const delFileItemListen = ref<UnlistenFn>();
const delFileResultListen = ref<UnlistenFn>();
const fileDataList = ref<FileModel[]>([]);

const delFileItem = ref("");
const delSuccessFlag = ref(false);

const startDel = () => {
    delSuccessFlag.value = false;
    scanFileComplete.value = false;
    console.log("startDel");
}

onMounted(async () => {
    fileItemListen.value = await listen('file-item', (event: any) => {
        //console.log("fileItemEventHandler: ", event.payload);
        currentScanFilePath.value = event.payload.path;
        scanFileNum.value += 1;
    });
    fileListResultListen.value = await listen('file-list-result', (event: any) => {
        //console.log("fileListResultEventHandler: ", event.payload);
        let t = new Date().getTime() - startTime.value.getTime();
        resultSubTitle.value = "共耗时 " + formatSeconds(t / 1000);

        let list = event.payload as ScanFileResult[];
        // let scanFileResult = sortByFileSize(list);
        resultTitle.value = "本次一共扫描 " + scanFileNum.value + " 个文件"

        fileDataList.value = list.map(i => {
            let first = i.files[0];
            let pathArray = i.files.map(f => f.file_path);
            return {
                md5: i.md5,
                name: first.file_name,
                num: i.files.length,
                size: first.size,
                sizeStr: formatFileSize(first.size),
                path: pathArray.slice(0, 5).join(', '),
                pathArray: pathArray,
            };
        });

        loading.value = false;
        scanFileComplete.value = true;
        //console.log("fileListResultSortSuccess");
    });

    delFileItemListen.value = await listen('del-file-item', (event: any) => {
        console.log("del-file-itemHandler: ", event.payload);
        delFileItem.value = event.payload.path;
    });

    delFileResultListen.value = await listen('del-file-result', (event: any) => {
        console.log("del-file-resultHandler: ", event.payload);
        delSuccessFlag.value = true;
        delFileItem.value = "";

        if (event.payload.all_flag) {
            fileDataList.value = [];
        } else {
            fileDataList.value = fileDataList.value.map(i => {
                let a = i.pathArray;
                i.pathArray = [a[0]];
                i.path = i.pathArray.join(', ');
                i.num = 1;
                return i;
            });
        }
    });
});

onUnmounted(() => {
    if (fileItemListen.value) {
        fileItemListen.value();
        //console.log("fileItemListen 已卸载");
    }
    if (fileListResultListen.value) {
        fileListResultListen.value();
        //console.log("fileListResultListen 已卸载");
    }
    if (delFileItemListen.value) {
        delFileItemListen.value();
    }
    if (delFileResultListen.value) {
        delFileResultListen.value();
    }
});

const startScan = async (dirData: string[]) => {
    delSuccessFlag.value = false;
    if (loading.value) {
        await sendCommand('stop');
        loading.value = false;
        return;
    }

    scanFileNum.value = 0;
    scanFileComplete.value = false;
    fileDataList.value = [];
    try {
        await sendCommand('file_list', { dir: dirData });
        message.success("启动扫描");
        scanFileComplete.value = false;
        loading.value = true;
        startTime.value = new Date();
        //console.log("start...");
    } catch (e: any) {
        message.error(e.stack);
    }


}
</script>

<template>

    <InputBar :loading="loading" @startScan="startScan" />
    <Result v-if="(scanFileComplete)" class="scanResult" :resultTitle="resultTitle" :resultSubTitle="resultSubTitle" />
    <Result v-if="(delSuccessFlag)" class="scanResult" resultTitle="全部删除成功" resultSubTitle="" />
    <Loading v-if="loading" :delFlag="false" :currentScanFilePath="currentScanFilePath" />
    <Loading v-if="(delFileItem)" :delFlag="true" :currentScanFilePath="delFileItem" />
    <FileTable v-if="fileDataList.length > 0" :dataList="fileDataList" @startDel="startDel" />

</template>

<style scoped>
.scanResult {
    margin-bottom: 20px;
}
</style>